const express = require('express');
const cookie = require('cookie-parser');
const multer = require('multer');
const globalConfig = require('./config');
const loader = require('./loader');
let app = new express();

/**
 * 文件上传下载
 * dest: '上传文件的路径'
 * upload.single('file'): file为指定文件的名字是file，获取时候可以通过 req.file 来获取，可见upload.js
 */
var upload = multer({ dest: 'uploads/' })

/**
 * 静态文件的文件夹所走的路径
 */
app.use(express.static(globalConfig['client_path']));

/**
 * cookies中间件
 * 获取cookies：req.cookies
 * 写入cookie：req.cookies('token','xxxxxxx');
 */
app.use(cookie());

/**
 * 用来接收post请求的参数 获取参数 req.body
 */
app.use(express.json());

/**
 * 拦截器
 */
app.get('/api/*', function (req, res, next) {
  // 获取cookie
  const cookies = req.cookies;
  console.log(cookies);
  // 写入cookie
  // rea.cookies('token','dsadsadada')
  next();
  if (cookies.token) {
    if (cookies.token) {
      next(); // 放行
    } else {
      // 重定向
      res.redirect('/login.html');
    }
  }
});

/**
 * 路由
 */
app.get('/api/getAllStudent', loader.get('/getAllStudent'));
app.post('/api/insertStudent', loader.get('/insertStudent'));

/**
 * 文件上传下载
 * dest: '上传文件的路径'
 * upload.single('file'): 是 input 的name属性的名字
 */

app.post('/upload', upload.single('file'), loader.get('/upload'));

app.listen(
  globalConfig['port'],
  () => console.log(`Example app listening on port ${globalConfig['port']}!`)
);


